package com.baosight.risk.service.rire.impl;

import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.fltd.FltdTaskService;
import com.baosight.risk.api.rire.RireReportWordService;
import com.baosight.risk.api.rire.RireRiskReportService;
import com.baosight.risk.api.workflow.AfterHandler;
import com.baosight.risk.api.workflow.UpdateHandler;
import com.baosight.risk.api.xtzy.IXtzyCompanyService;
import com.baosight.risk.api.xtzy.IXtzyIntegralService;
import com.baosight.risk.base.entity.MultipleUpdateStatus;
import com.baosight.risk.base.mapper.BaseMapper;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.enums.IntegralType;
import com.baosight.risk.common.manager.AsyncManager;
import com.baosight.risk.common.quartz.RireRiskReportTask;
import com.baosight.risk.common.utils.*;
import com.baosight.risk.mapper.fltd.FltdTaskMapper;
import com.baosight.risk.mapper.riim.RiimRiskGoalDetailMapper;
import com.baosight.risk.mapper.riim.RiimRiskImportMapper;
import com.baosight.risk.mapper.rire.RireRiskEventMapper;
import com.baosight.risk.mapper.rire.RireRiskTargetMapper;
import com.baosight.risk.mapper.rire.RireRiskWarningStatusMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringRuleMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringStatusMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringTargetMapper;
import com.baosight.risk.mapper.system.SysRoleMapper;
import com.baosight.risk.mapper.xtdc.XtdcAttachMapper;
import com.baosight.risk.mapper.xtzy.XtzyRoleUserMapper;
import com.baosight.risk.mapper.xtzy.XtzyUserMapper;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import com.baosight.risk.service.riim.entity.RiimRiskImport;
import com.baosight.risk.service.riim.vo.RiimRiskImportVO;
import com.baosight.risk.service.rire.entity.RireRiskEvent;
import com.baosight.risk.service.rire.entity.RireRiskTarget;
import com.baosight.risk.service.rire.entity.RireRiskWarningStatus;
import com.baosight.risk.service.rire.vo.RireRiskEventVO;
import com.baosight.risk.service.rire.vo.RireRiskVO;
import com.baosight.risk.service.rire.vo.RiskWarningStatusVO;
import com.baosight.risk.service.rire.vo.RiskWarningVO;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaring;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringRule;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringStatus;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringTarget;
import com.baosight.risk.service.riwa.vo.RiwaRiskWaringRuleVO;
import com.baosight.risk.service.riwa.vo.RiwaRiskWaringVO;
import com.baosight.risk.service.system.entity.SysRole;
import com.baosight.risk.service.xtdc.entity.XtdcAttach;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;
import com.baosight.risk.service.xtzy.entity.XtzyRoleUser;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import com.baosight.risk.web.freemarker.FreeMarkerController;
import com.baosight.risk.web.netty.SocketIO;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RireRiskReportServiceImpl extends BaseServiceImpl<RiimRiskImport> implements RireRiskReportService, UpdateHandler, AfterHandler {

    @Autowired
    private RiimRiskImportMapper riskImportMapper;
    @Autowired
    private RireRiskTargetMapper rireRiskTargetMapper;
    @Autowired
    private RireRiskEventMapper rireRiskEventMapper;
    @Autowired
    private RireRiskWarningStatusMapper rireRiskWarningStatusMapper;

    @Autowired
    private XtzyRoleUserMapper xtzyRoleUserMapper;

    @Autowired
    private XtzyUserMapper xtzyUserMapper;

    @Autowired
    private IXtzyIntegralService integralService;

    @Autowired
    private IXtzyCompanyService xtzyCompanyService;

    @Autowired
    private RireReportWordService reportWordService;

    @Autowired
    private FreeMarkerController freeMarkerController;

    @Autowired
    private XtdcAttachMapper xtdcAttachMapper;
    @Autowired
    private RiimRiskGoalDetailMapper goalDetailtMapper;

    @Autowired
    private RiwaRiskWaringMapper riskWaringMapper;
    @Autowired
    private RiwaRiskWaringStatusMapper riskWaringStatusMapper;
    @Autowired
    private RiwaRiskWaringRuleMapper riskWaringRuleMapper;
    @Autowired
    private RiwaRiskWaringTargetMapper riskWaringTatgetMapper;
    @Autowired
    private XtdcAttachMapper attachMapper;

    @Autowired
    private FltdTaskService fltdTaskService;
    @Autowired
    private SocketIO socketServer;
    @Autowired
    private FltdTaskMapper fltdTaskMapper;


    @Autowired
    private FltdProcessService fltdProcessService;

    @Override
    public BaseMapper getMapper() {
        return riskImportMapper;
    }

    @Override
    public List<RiskWarningStatusVO> selectList(RireRiskWarningStatus warningStatus) {
        List<RiskWarningStatusVO> list = new ArrayList<>();
        if (!ShiroUtils.getUser().isAdmin()) {
            List<XtzyCompany> parantAndChildrens = xtzyCompanyService.getParantAndChildrens(ShiroUtils.getUser().getExt1());
            List<String> deptList = parantAndChildrens.stream().map(XtzyCompany::getCompCode).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(deptList)) {
                list = rireRiskWarningStatusMapper.selectList(warningStatus, deptList);

            }
        }else{
            servicePage();
            list = rireRiskWarningStatusMapper.selectList(warningStatus, null);
        }
        for (RiskWarningStatusVO vo : list) {
            vo.setRiskName(vo.getExt3());
        }
        return list;
    }

    @Override
    public List<RireRiskWarningStatus> getByIds(List<String> ids) {
    	if(CollectionUtils.isNotEmpty(ids)){
    		return rireRiskWarningStatusMapper.getByIds(ids);
    	}
        return new ArrayList<RireRiskWarningStatus>();
    }

    @Override
    public Integer saveRireRisk(RireRiskVO rireRiskVO, XtzyUser user) {
        //先删除，后新增;根据披露报告删除披露报告子表信息
        deleteByReport(rireRiskVO.getId());
        //修改披露报告
        rireRiskVO = (RireRiskVO) BeanUtils.updateBean(rireRiskVO);
        if(CollectionUtils.isNotEmpty(rireRiskVO.getRiskWaringVOList())) {
            String ext4 = rireRiskVO.getRiskWaringVOList().get(0).getExt4();//自定义模型整体结论
            if (ext4!=null){
                rireRiskVO.setWaringStatus(ext4);
            }
        }

        rireRiskWarningStatusMapper.updateByPrimaryKeySelective(rireRiskVO);
        //再新增风险指标
        if (CollectionUtils.isNotEmpty(rireRiskVO.getRiskTargetList())) {
            for (RireRiskTarget riskTarget : rireRiskVO.getRiskTargetList()) {
                riskTarget.setQuarterCode(rireRiskVO.getQuarterCode());
                riskTarget.setQuarterName(rireRiskVO.getQuarterName());
                riskTarget.setImportGuid(rireRiskVO.getImportGuid());
                riskTarget.setRiskId(rireRiskVO.getRiskId());
                riskTarget.setImportReportGuid(rireRiskVO.getId());
                riskTarget.setManageCompCode(rireRiskVO.getManageCompCode());
                riskTarget.setManageCompName(rireRiskVO.getManageCompName());
                riskTarget = (RireRiskTarget) BeanUtils.initBean(riskTarget);
                rireRiskTargetMapper.insert(riskTarget);
            }
        }
        //再新增风险事件
        if (CollectionUtils.isNotEmpty(rireRiskVO.getRiskEventList())) {
            for (RireRiskEvent riskEvent : rireRiskVO.getRiskEventList()) {
                riskEvent.setImportGuid(rireRiskVO.getImportGuid());
                riskEvent.setRiskId(rireRiskVO.getImportGuid());
                riskEvent.setImportReportGuid(rireRiskVO.getId());
                riskEvent.setDeleteFlag("1");
                riskEvent.setManageCompCode(rireRiskVO.getManageCompCode());
                riskEvent.setManageCompName(rireRiskVO.getManageCompName());
                riskEvent = (RireRiskEvent) BeanUtils.initBean(riskEvent);
                rireRiskEventMapper.insert(riskEvent);
                //添加积分
                integralService.insertIntegral(user, IntegralType.Type9);

            }
        }
        //预警模型
        riwaRiskWaringInfo(rireRiskVO);
        return 1;
    }

    public Integer riwaRiskWaringInfo(RireRiskVO rireRiskVO) {
        //新增数据
        if (CollectionUtils.isEmpty(rireRiskVO.getRiskWaringVOList())) {
            return null;
        }
        //新增重点风险预警模型
        for (RiwaRiskWaringVO riwaRiskWaringVO : rireRiskVO.getRiskWaringVOList()) {
            String waringId = riwaRiskWaringVO.getId();
            String ext1 = riwaRiskWaringVO.getExt1();
            String ext2 = riwaRiskWaringVO.getExt2();
            String ext3 = riwaRiskWaringVO.getExt3();
            BeanUtils.copyBeanProp(riwaRiskWaringVO, rireRiskVO);
            riwaRiskWaringVO.setImportGuid(rireRiskVO.getImportGuid());
            riwaRiskWaringVO.setRiskId(rireRiskVO.getRiskId());
            riwaRiskWaringVO.setImportReportGuid(rireRiskVO.getId());
            riwaRiskWaringVO.setExt1(ext1);
            riwaRiskWaringVO.setExt2(ext2);
            riwaRiskWaringVO.setExt3(ext3);
            riwaRiskWaringVO.setManageCompCode(rireRiskVO.getManageCompCode());
            riwaRiskWaringVO.setManageCompName(rireRiskVO.getManageCompName());
            riwaRiskWaringVO = (RiwaRiskWaringVO) BeanUtils.initBean(riwaRiskWaringVO);
            if (StringUtils.isNotEmpty(waringId)) {
                riwaRiskWaringVO.setId(waringId);
            }
            // TODO 清空预警模型状态 -- 这里的状态是拷贝披露报状态，需要重新定义。
            riwaRiskWaringVO.setStatus("");
            riwaRiskWaringVO.setStatusName("");
            RiwaRiskWaring exist = riskWaringMapper.selectByPrimaryKey(riwaRiskWaringVO.getId());
            if (exist != null) {
                riskWaringMapper.updateByPrimaryKeySelective(riwaRiskWaringVO);
                return 1;
            } else {
                riskWaringMapper.insert(riwaRiskWaringVO);
            }

            //新增重点风险预警模型-预警状态
            if (CollectionUtils.isNotEmpty(riwaRiskWaringVO.getRiskWaringStatusVOList())) {
                for (RiwaRiskWaringVO.RiwaRiskWaringStatusVO waringStatusVO : riwaRiskWaringVO.getRiskWaringStatusVOList()) {
                    waringStatusVO.setWarningModelGuid(riwaRiskWaringVO.getId());
                    waringStatusVO.setImportGuid(rireRiskVO.getId());
                    waringStatusVO.setRiskId(rireRiskVO.getRiskId());
                    waringStatusVO = (RiwaRiskWaringVO.RiwaRiskWaringStatusVO) BeanUtils.initBean(waringStatusVO);
                    riskWaringStatusMapper.insert(waringStatusVO);
                    //新增重点风险预警模型-预警规则
                    if (CollectionUtils.isNotEmpty(waringStatusVO.getRiskWaringRuleVOList())) {
                        for (RiwaRiskWaringRuleVO riskWaringRuleVO : waringStatusVO.getRiskWaringRuleVOList()) {
                            riskWaringRuleVO.setWarningModelGuid(riwaRiskWaringVO.getId());
                            riskWaringRuleVO.setImportGuid(rireRiskVO.getId());
                            riskWaringRuleVO.setRiskId(rireRiskVO.getRiskId());
                            riskWaringRuleVO.setWaringStatusGuid(waringStatusVO.getId());
                            riskWaringRuleVO = (RiwaRiskWaringRuleVO) BeanUtils.initBean(riskWaringRuleVO);
                            riskWaringRuleMapper.insert(riskWaringRuleVO);
                            //新增重点风险预警模型-预警风险指标
                            if (CollectionUtils.isNotEmpty(riskWaringRuleVO.getRiskWaringTargetList())) {
                                for (RiwaRiskWaringTarget riskWaringTarget : riskWaringRuleVO.getRiskWaringTargetList()) {
                                    riskWaringTarget.setWarningModelGuid(riwaRiskWaringVO.getId());
                                    riskWaringTarget.setImportGuid(rireRiskVO.getId());
                                    riskWaringTarget.setRiskId(rireRiskVO.getRiskId());
                                    riskWaringTarget.setWaringStatusGuid(waringStatusVO.getId());
                                    riskWaringTarget.setWarningRuleId(riskWaringRuleVO.getId());
                                    riskWaringTarget = (RiwaRiskWaringTarget) BeanUtils.initBean(riskWaringTarget);
                                    riskWaringTatgetMapper.insert(riskWaringTarget);
                                }
                            }
                        }
                    }
                }
            }
        }
        return 1;
    }


    public void deleteByReport(String warningId) {
        //删除风险指标
        rireRiskTargetMapper.deleteByImportId(warningId);
        //删除风险时间
        rireRiskEventMapper.deleteByImportId(warningId);
        //删除预警模型
        List<RiwaRiskWaring> waringList = riskWaringMapper.getWaringByImportId(warningId);
        if (CollectionUtils.isNotEmpty(waringList)) {
            for (RiwaRiskWaring riwaRiskWaring : waringList) {
                //删除预警状态
                riskWaringStatusMapper.deleteByWaringId(riwaRiskWaring.getId());
                //删除预警规则
                riskWaringRuleMapper.deleteByWaringId(riwaRiskWaring.getId());
                //删除预警指标
                riskWaringTatgetMapper.deleteByWaringId(riwaRiskWaring.getId());
                //删除预警模型
                riskWaringMapper.deleteByImportId(warningId);
            }
        }

    }

    /**
     * @param importId      被流转ID
     * @param circulationId 流转ID
     * @return
     */
    @Override
    public Integer saveByLastYear(String importId, String circulationId, String quarter, XtzyUser user) {
        //根据流转ID找到披露报告
        RiskWarningVO RiskWarningVO = getById(circulationId);
        //根据重点风险ID找到重点风险
        RiimRiskImport riskImport = riskImportMapper.selectByPrimaryKey(importId);
        //替换
        BeanUtils.copyBeanProp(RiskWarningVO, riskImport);
        //=========把ID赋值为空，然后新增================
        //风险指标
        if (CollectionUtils.isEmpty(RiskWarningVO.getRireRiskVOList())) {
            log.error("【" + riskImport.getRiskName() + "】该重点风险" + quarter + "季度没有披露报告");
            return 0;
        }
        for (RireRiskVO rireRiskVO : RiskWarningVO.getRireRiskVOList()) {
            rireRiskVO.setId(null);
            //风险指标
            if (CollectionUtils.isNotEmpty(rireRiskVO.getRiskTargetList())) {
                for (RireRiskTarget riskTarget : rireRiskVO.getRiskTargetList()) {
                    riskTarget.setId(null);
                }
            }
            //风险事件
            if (CollectionUtils.isNotEmpty(rireRiskVO.getRiskEventList())) {
                for (RireRiskEvent riskEvent : rireRiskVO.getRiskEventList()) {
                    riskEvent.setId(null);
                }
            }
            //预警模型
            if (CollectionUtils.isNotEmpty(rireRiskVO.getRiskWaringVOList())) {
                for (RiwaRiskWaringVO riwaRiskWaringVO : rireRiskVO.getRiskWaringVOList()) {
                    riwaRiskWaringVO.setId(null);
                    //重点风险预警模型-预警状态
                    if (CollectionUtils.isNotEmpty(riwaRiskWaringVO.getRiskWaringStatusVOList())) {
                        for (RiwaRiskWaringVO.RiwaRiskWaringStatusVO waringStatusVO : riwaRiskWaringVO.getRiskWaringStatusVOList()) {
                            waringStatusVO.setId(null);
                            //重点风险预警模型-预警规则
                            if (CollectionUtils.isNotEmpty(waringStatusVO.getRiskWaringRuleVOList())) {
                                for (RiwaRiskWaringRuleVO riskWaringRuleVO : waringStatusVO.getRiskWaringRuleVOList()) {
                                    riskWaringRuleVO.setId(null);
                                    //重点风险预警模型-预警风险指标
                                    if (CollectionUtils.isNotEmpty(riskWaringRuleVO.getRiskWaringTargetList())) {
                                        for (RiwaRiskWaringTarget riskWaringTarget : riskWaringRuleVO.getRiskWaringTargetList()) {
                                            riskWaringTarget.setId(null);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //新增数据
            saveRireRisk(rireRiskVO, user);
        }
        return 1;
    }


    @Override
    public RiskWarningVO getById(String id) {
        RiskWarningVO riskWarningVO = new RiskWarningVO();
        RireRiskWarningStatus status = rireRiskWarningStatusMapper.selectByPrimaryKey(id);
        RiimRiskImport riskImport = riskImportMapper.selectByPrimaryKey(status.getImportGuid());
        BeanUtils.copyBeanProp(riskWarningVO, riskImport);
        List<RireRiskVO> rireRiskVOList = new ArrayList<>();
        RireRiskVO rireRiskVO = new RireRiskVO();
        BeanUtils.copyBeanProp(rireRiskVO, status);
        riskWarningVO.setExt1(status.getExt1());
        riskWarningVO.setExt5(riskImport.getSpecialFlag());
        riskWarningVO.setQuarterCurrent(status.getQuarterCode());
        riskWarningVO.setWarningStatus(status.getWaringStatus());
        //重点风险披露报告===风险指标
        List<RireRiskTarget> rireRiskTargetList = rireRiskTargetMapper.getTargetByImportId(status.getId());
        rireRiskVO.setRiskTargetList(rireRiskTargetList);
        //重点风险披露报告===风险事件
        List<RireRiskEvent> rireRiskEventList = rireRiskEventMapper.getEventByImportId(status.getId());
        rireRiskVO.setRiskEventList(rireRiskEventList);
        //重点风险披露报告===预警模型
        List<RiwaRiskWaringVO> riskWaringVOList = getRiskWaring(status.getId());
        rireRiskVO.setRiskWaringVOList(riskWaringVOList);
        rireRiskVOList.add(rireRiskVO);

        riskWarningVO.setRireRiskVOList(rireRiskVOList);
        return riskWarningVO;
    }

    public List<RiwaRiskWaringVO> getRiskWaring(String importReportGuid) {
        List<RiwaRiskWaringVO> riwaRiskWaringVOList = new ArrayList<>();
        //找到披露报告
        List<RiwaRiskWaring> riskWaringList = riskWaringMapper.getWaringByImportId(importReportGuid);
        if (CollectionUtils.isNotEmpty(riskWaringList)) {
            for (RiwaRiskWaring waring : riskWaringList) {
                //预警模型
                RiwaRiskWaringVO waringVO = new RiwaRiskWaringVO();
                BeanUtils.copyBeanProp(waringVO, waring);
                //预警状态
                List<RiwaRiskWaringStatus> waringStatusList = riskWaringStatusMapper.getWaringStatusByWaringId(waringVO.getId());
                List<RiwaRiskWaringVO.RiwaRiskWaringStatusVO> riskWaringStatusVOList = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(waringStatusList)) {
                    for (RiwaRiskWaringStatus waringStatus : waringStatusList) {
                        RiwaRiskWaringVO.RiwaRiskWaringStatusVO waringStatusVO = new RiwaRiskWaringVO.RiwaRiskWaringStatusVO();
                        BeanUtils.copyBeanProp(waringStatusVO, waringStatus);
                        //预警规则
                        List<RiwaRiskWaringRule> riskWaringRuleList = riskWaringRuleMapper.getWaringRuleByStatusId(waringStatus.getId());
                        List<RiwaRiskWaringRuleVO> riskWaringRuleVOList = new ArrayList<>();
                        if (CollectionUtils.isNotEmpty(riskWaringRuleList)) {
                            for (RiwaRiskWaringRule riskWaringRule : riskWaringRuleList) {
                                RiwaRiskWaringRuleVO riwaRiskWaringRuleVO = new RiwaRiskWaringRuleVO();
                                BeanUtils.copyBeanProp(riwaRiskWaringRuleVO, riskWaringRule);
                                //预警规则指标
                                List<RiwaRiskWaringTarget> riskWaringTargetList = riskWaringTatgetMapper.getWaringTargetByRuleId(riskWaringRule.getId());
                                riwaRiskWaringRuleVO.setRiskWaringTargetList(riskWaringTargetList);
                                riskWaringRuleVOList.add(riwaRiskWaringRuleVO);
                            }
                        }
                        waringStatusVO.setRiskWaringRuleVOList(riskWaringRuleVOList);
                        riskWaringStatusVOList.add(waringStatusVO);
                    }
                }
                waringVO.setRiskWaringStatusVOList(riskWaringStatusVOList);
                riwaRiskWaringVOList.add(waringVO);
            }
        }
        return riwaRiskWaringVOList;
    }

    @Override
    public List<String> selectGoalDetail(String importId, String targetNo, String compCode) {
        return goalDetailtMapper.selectGoalDetail(importId, targetNo, compCode);
    }

    @Override
    public Integer updateStatus(MultipleUpdateStatus updateStatus) {
        rireRiskWarningStatusMapper.updateStatus(updateStatus);
        return 1;
    }


    @Override
    public RireRiskTarget predictNextValue(RireRiskTarget target) {
        Map<String, Object> maps = new HashMap<>();
        List<RireRiskTarget> list = new ArrayList<>();
        list.add(target);
        maps.put("data", list);

        String url = ReadProperties.getValueString("python.predict.url");
        //调用外部接口获取数据
        String result = HttpUtils.sendJsonPost(url, JSONObject.fromObject(maps));

        if (StringUtils.isEmpty(result)) {
            System.out.println("返回结果==============" + result);
            target.setNextValue("0");
            return target;
        }
        JSONObject json = JSONObject.fromObject(result);
        JSONArray array = JSONArray.fromObject(json.get("data"));
        //接受外部数据
        list = JSONArray.toList(array, new RireRiskTarget(), new JsonConfig());
        return list.get(0);
    }

    /**
     * status	当前节点状态
     * nextStatus	下一节点状态
     * nextStatusName	下一节点状态名称
     * acctYear	当前年度
     * quarterCurrent	当前季度
     * deptCode	填报人的部门编码
     * bizGuid 业务id
     * taskGuid 项目id(重点风险id)
     * context 审批意见
     * submitType 提交、回退、结束, 值：(submit, reject, end)
     *
     * @param params
     */
    @Override
    public boolean updateStatus(Map<String, Object> params) {
        RireRiskWarningStatus status = new RireRiskWarningStatus();
        String id = (String) params.get("bizGuid");
        String planStatus = (String) params.get("nextStatus");
        String planStatusName = (String) params.get("nextStatusName");
        status = (RireRiskWarningStatus) BeanUtils.updateBean(status);
        status.setId(id);
        status.setStatus(planStatus);
        status.setStatusName(planStatusName);
        if(params.get("quartzParam")!=null && "1".equals(params.get("quartzParam").toString())){
            if ("B06".equals(params.get("status"))) {
                //添加审核人
                status.setGroupUserCode(params.get("currentExaminerCode").toString());
                status.setGroupUserName(params.get("currentExaminerName").toString());
            } else if ("B02".equals(params.get("status"))) {
                //添加审批人
                status.setDeptUserCode(params.get("currentExaminerCode").toString());
                status.setDeptUserName(params.get("currentExaminerName").toString());
            }
        }else {
            if ("B06".equals(params.get("status"))) {
                //添加审核人
                status.setGroupUserCode(getUser().getUserCode());
                status.setGroupUserName(getUser().getUserDesc());
            } else if ("B02".equals(params.get("status"))) {
                //添加审批人
                status.setDeptUserCode(getUser().getUserCode());
                status.setDeptUserName(getUser().getUserDesc());
            }
        }


        rireRiskWarningStatusMapper.updateByPrimaryKeySelective(status);
        if("B09".equals(params.get("nextStatus"))){
            RiskWarningStatusVO statusVO=rireRiskWarningStatusMapper.getWarningById(id);
            RireRiskEventVO eventVO=new RireRiskEventVO();
            eventVO.setImportGuid(statusVO.getImportGuid());
            List<RireRiskEvent> riskEventList=rireRiskEventMapper.queryRiskEventData(eventVO);
            for (RireRiskEvent item: riskEventList) {
                rireRiskEventMapper.updateAuditDate(item.getId(),new Date());
            }
        }
        return true;
    }


    /**
     * status	当前节点状态
     * nextStatus	下一节点状态
     * nextStatusName	下一节点状态名称
     * acctYear	当前年度
     * quarterCurrent	当前季度
     * deptCode	填报人的部门编码
     * bizGuid 业务id
     * taskGuid 项目id(重点风险id)
     * context 审批意见
     * submitType 提交、回退、结束, 值：(submit, reject, end)
     *
     */
    @Override
    public boolean doAfter(Map<String, Object> params) {
//        AsyncManager.me().execute(new TimerTask() {
//            @Override
//            public void run() {
                try {
                    if ("sbumit".equals(params.get("submitType").toString()) && "B05".equals(params.get("status").toString())){

                        String[] roleKeys={"COMP01","COMP05"};
                        List<XtzyRoleUser> roleUsers=xtzyRoleUserMapper.selectAllByRoleKey(roleKeys);
                        String taskGuid = params.get("taskGuid").toString();
                        RiimRiskImport riimImport = riskImportMapper.selectByPrimaryKey(taskGuid);
                        this.noticeDutyUser(riimImport,roleUsers);
                        this.submitTypeData(params,"sbumit");
                    }else{
                        if("reject".equals(params.get("submitType").toString()) && "B05".equals(params.get("status").toString())){
                            this.submitTypeData(params,"reject");
                        }
                        String reportId = (String) params.get("bizGuid");
                        String riskName = (String) params.get("bizName");
                        String acctYear = (String) params.get("acctYear");
                        String quarterCurrent = (String) params.get("quarterCurrent");
                        Map map = reportWordService.reportWord(reportId, "2");
                        if (map.isEmpty()) {
                            log.error("数据为空！");
                            throw new Exception("数据为空");
                        }
                        String sourceModel = "T_RIRE_RISK_WARNING_STATUS_"+acctYear+'_'+quarterCurrent;
//                    String wordName = acctYear + "年" + quarterCurrent + "季度" + riskName;
                        String wordName = riskName.replace("<", "").replace(">", "");
                        if(map.get("specialFlag")!=null && "Y".equals(map.get("specialFlag").toString()) ){
                            freeMarkerController.exportPDF(map, "specialReport.ftl", wordName, reportId, sourceModel, true);
                        }else{
                            freeMarkerController.exportPDF(map, "report.ftl", wordName, reportId, sourceModel, true);
                        }


                    }
                }catch (Exception e){
                    log.error("生成披露报告pdf异常："+e.getMessage());
                    return false;
                }
//            }
//        });
        return true;
    }

    private void submitTypeData(Map<String, Object> params,String submitType)throws Exception{
        try {
            //根据biz_guid（披露报告id）,根据所选披露报告，
            String bizGuid=params.get("bizGuid").toString();
            RireRiskWarningStatus parentWarningStatus=rireRiskWarningStatusMapper.getWarningById(bizGuid);
            //获取重点风险ID,检查是否存在子数据
            RiimRiskImportVO paramImport=new RiimRiskImportVO();
            paramImport.setParentId(parentWarningStatus.getImportGuid());
            List<RiimRiskImport> importList=riskImportMapper.selectList(paramImport);
            for (RiimRiskImport item : importList){
                //根据下属单位（比如：梅钢公司）的重点风险清单的主键获取业务、流程编码、节点（node_code=‘C01’）、状态（open）获取下属单位实施披露报告的待办
                RireRiskWarningStatus riskWarningStatus=new RireRiskWarningStatus();
                riskWarningStatus.setImportGuid(item.getId());
                List<RireRiskWarningStatus> subWarningStatusList=rireRiskWarningStatusMapper.select(riskWarningStatus);
                for (RireRiskWarningStatus statusItem:subWarningStatusList){
                    if(StringUtils.isNotEmpty(item.getDutyUserCode())){
                        XtzyUser xtzyUser =xtzyUserMapper.selectByName(item.getDutyUserCode());
                        FltdTaskVO paramTask=new FltdTaskVO();
                        paramTask.setFlowNo("jidifengxianpilubaogao");
                        paramTask.setBizGuid(statusItem.getId());
                        paramTask.setNodeCode("C01");
                        paramTask.setStatus("open");
                        List<FltdTask> taskList=fltdTaskMapper.selectTaskList(paramTask);
                        if(taskList.size()>0){
                            FltdTaskVO taskVoParam=new FltdTaskVO();
                            BeanUtils.copyBeanProp(taskVoParam, taskList.get(0));
                            if("sbumit".equals(submitType)){
                                fltdProcessService.doSubmit(xtzyUser,taskVoParam);
                            }
                            if("reject".equals(submitType)){
                                fltdProcessService.doCancel(xtzyUser,taskVoParam);
                            }
                        }
                    }
                }

            }
        }catch (Exception e){
            throw new Exception(e.getMessage());
        }

    }

    private void noticeDutyUser(RiimRiskImport riimImport,List<XtzyRoleUser> roleUsers){
        XtzyUser sysUser = ShiroUtils.getUser();
        for (XtzyRoleUser  roleUser:roleUsers){
            FltdTask taskVO = (FltdTask) BeanUtils.initBean(new FltdTask());
            taskVO.setTodoGuid(UUID.randomUUID().toString());
            taskVO.setFlowNo("chakanfengxianshijian");
            taskVO.setFlowName("查看本季度风险事件列表");
            taskVO.setAcctYear(DateUtils.format(new Date(), "yyyy"));
            taskVO.setQuarterCode(DateUtils.getQuarter(new Date()));
            taskVO.setQuarterName(DateUtils.getQuarterName(taskVO.getQuarterCode()));
            taskVO.setFirstUserCode(sysUser.getUserCode());
            taskVO.setFirstUserName(sysUser.getUserDesc());
            taskVO.setGroupFlag("N");
            taskVO.setBeforeUserCode(sysUser.getUserCode());
            taskVO.setBeforeUserName(sysUser.getUserDesc());
            taskVO.setCurrUserCode(roleUser.getUserCode());
            taskVO.setCurrUserName(roleUser.getUserDesc());
            taskVO.setCompCode(roleUser.getCompCode());
            taskVO.setCompName(roleUser.getCompName());
            taskVO.setDeptCode(roleUser.getCompCode());
            taskVO.setDeptName(roleUser.getCompName());
            taskVO.setPageUrl("/rire/checkRiskEvent");
            taskVO.setBizGuid(riimImport.getId());
            taskVO.setBizName(riimImport.getRiskName());
            taskVO.setBizDesc( riimImport.getAcctYear() + "年" + DateUtils.getQuarter(new Date()) + "季度重点风险事件");
            taskVO.setTodoType("2");
            taskVO.setStatus("open");
            taskVO.setStatusName("进行中");
            taskVO.setFactStartDate(new Date());

            /*if (fltdTaskService.insert(taskVO) > 0) {
                // 发送通知
                *//*XtzyUser userMsg = new XtzyUser();
                userMsg.setUserCode(roleUser.getUserCode());
                userMsg.setUserDesc(roleUser.getUserDesc());
                userMsg.setExt1(roleUser.getCompCode());
                userMsg.setExt2(roleUser.getCompName());
                userMsg.setExt3("open");
                socketServer.sendMsgToAll(userMsg);*//*
            }
*/




        }
    }


    @Override
    public Map selctIndex(String sortFlag) throws Exception {
        String year = "";
        String quarterCurrent = "";
        Map map = new HashMap();
        //获得最新上传的公司披露报告
        XtdcAttach companyReport = attachMapper.getCompanyReport();
        if (companyReport != null) {
            String sourceGuid = companyReport.getSourceGuid();
            //最新年度
            year = sourceGuid.substring(4, 8);
            //最新季度
            quarterCurrent = sourceGuid.substring(9, 10);
        } else {
            return map;
        }
        map.put("currentQuarter", quarterCurrent);
        //拼裝查詢條件
        RireRiskWarningStatus query = new RireRiskWarningStatus();
        query.setAcctYear(year);
        query.setQuarterCode(quarterCurrent);
        if(!"BGTA".equals(ShiroUtils.getUser().getManageCompCode())){
            query.setManageCompCode( ShiroUtils.getUser().getManageCompCode());
        }
        query.setStatus("B09");
        //最新年度季度
        List<RiskWarningStatusVO> list = selectList(query);
        if (CollectionUtils.isEmpty(list)) {
            return map;
        }
        //计算同比
        map = jisuantongbi(quarterCurrent, year, list, map);

        Map<String, List<RireRiskWarningStatus>> statusMap = new HashMap<>();
        //flag=1-->本期结论顺序
        //flag=2-->本期结论倒序
        //flag=3-->下期结论顺序
        //flag=4-->下期结论倒序

        String desc = "总体预警：本期共有" + list.size() + "个重点风险；";
        List<RireRiskWarningStatus> resultList = new ArrayList<>();
        try {
            statusMap = list.stream().collect(Collectors.groupingBy(RireRiskWarningStatus::getWaringStatus));
            desc = sortDate(resultList, statusMap, desc);
            map.put("desc", desc);
            // 默认本期结论倒序 红》橙》黄》绿》白
            if (!StringUtils.isNotEmpty(sortFlag)) {
                sortFlag = "2";
            }
            if ("1".equals(sortFlag)) {
                map.put("statusList", resultList);
                return map;
            }
            resultList.clear();

            if ("3".equals(sortFlag) || "4".equals(sortFlag)) {
                statusMap = list.stream().collect(Collectors.groupingBy(RireRiskWarningStatus::getNextWaringStatus));
            }
        } catch (Exception e) {
            throw new Exception("数据有误！");
        }

        if ("2".equals(sortFlag) || "4".equals(sortFlag)) {
            sortDate(resultList, statusMap, false);
        } else {
            sortDate(resultList, statusMap, true);
        }
        map.put("statusList", resultList);
        return map;
    }



    /**
     * @param quarterCurrent
     * @param year
     * @param list
     * @param map
     * @return
     */
    private Map jisuantongbi(String quarterCurrent, String year, List<RiskWarningStatusVO> list, Map map) {
        //上一季度
        String year1;
        String quarter1;
        if ("1".equals(quarterCurrent)) {
            year1 = String.valueOf(Integer.valueOf(year) - 1);
            quarter1 = "4";
        } else {
            year1 = year;
            quarter1 = String.valueOf(Integer.valueOf(quarterCurrent) - 1);
        }
        //拼裝查詢條件
        RireRiskWarningStatus query = new RireRiskWarningStatus();
        query.setAcctYear(year1);
        query.setQuarterCode(quarter1);
        query.setStatus("B09");
        List<RiskWarningStatusVO> list1 = selectList(query);
        int status = list.size() - list1.size();
        String rate = tongbi(list, list1);
        if (rate == null) {
            return map;
        }
        map.put("currentRate", rate);
        map.put("currentStatus", status >= 0 ? "1" : "0");
        map.put("currentQuarter", list.get(0).getQuarterCode());
        return map;
    }

    public String sortDate(List<RireRiskWarningStatus> resultList,
                           Map<String, List<RireRiskWarningStatus>> statusMap, String desc) {
        if (CollectionUtils.isNotEmpty(statusMap.get("green"))) {
            resultList.addAll(statusMap.get("green"));
            desc = desc + "绿色指标" + statusMap.get("green").size() + "个；";
        }
        if (CollectionUtils.isNotEmpty(statusMap.get("yellow"))) {
            resultList.addAll(statusMap.get("yellow"));
            desc = desc + "黄色指标" + statusMap.get("yellow").size() + "个；";
        }
        if (CollectionUtils.isNotEmpty(statusMap.get("orange"))) {
            resultList.addAll(statusMap.get("orange"));
            desc = desc + "橙色指标" + statusMap.get("orange").size() + "个；";
        }
        if (CollectionUtils.isNotEmpty(statusMap.get("red"))) {
            resultList.addAll(statusMap.get("red"));
            desc = desc + "红色指标" + statusMap.get("red").size() + "个；";
        }
        if (CollectionUtils.isNotEmpty(statusMap.get("black"))) {
            resultList.addAll(statusMap.get("black"));
            desc = desc + "黑色指标" + statusMap.get("black").size() + "个；";
        }
        if (CollectionUtils.isNotEmpty(statusMap.get(""))) {
            resultList.addAll(statusMap.get(""));
        }
        return desc;
    }

    public void sortDate(List<RireRiskWarningStatus> resultList,
                         Map<String, List<RireRiskWarningStatus>> statusMap, Boolean flag) {
        //flag是true的时候，顺序；flag是false的时候，倒序；
        if (flag) {
            if (CollectionUtils.isNotEmpty(statusMap.get(""))) {
                resultList.addAll(statusMap.get(""));
            }
            if (CollectionUtils.isNotEmpty(statusMap.get("green"))) {
                resultList.addAll(statusMap.get("green"));
            }
            if (CollectionUtils.isNotEmpty(statusMap.get("yellow"))) {
                resultList.addAll(statusMap.get("yellow"));
            }
            if (CollectionUtils.isNotEmpty(statusMap.get("orange"))) {
                resultList.addAll(statusMap.get("orange"));
            }
            if (CollectionUtils.isNotEmpty(statusMap.get("red"))) {
                resultList.addAll(statusMap.get("red"));
            }
            if (CollectionUtils.isNotEmpty(statusMap.get("black"))) {
                resultList.addAll(statusMap.get("black"));
            }
        } else {
            if (CollectionUtils.isNotEmpty(statusMap.get("black"))) {
                resultList.addAll(statusMap.get("black"));
            }
            if (CollectionUtils.isNotEmpty(statusMap.get("red"))) {
                resultList.addAll(statusMap.get("red"));
            }
            if (CollectionUtils.isNotEmpty(statusMap.get("orange"))) {
                resultList.addAll(statusMap.get("orange"));
            }
            if (CollectionUtils.isNotEmpty(statusMap.get("yellow"))) {
                resultList.addAll(statusMap.get("yellow"));
            }
            if (CollectionUtils.isNotEmpty(statusMap.get("green"))) {
                resultList.addAll(statusMap.get("green"));
            }
            if (CollectionUtils.isNotEmpty(statusMap.get(""))) {
                resultList.addAll(statusMap.get(""));
            }
        }


    }

    private String tongbi(List<RiskWarningStatusVO> list, List<RiskWarningStatusVO> list1) {
        List<RireRiskWarningStatus> list2 = list.stream().filter(o -> !o.getWaringStatus().equals("green")).collect(Collectors.toList());
        List<RireRiskWarningStatus> list3 = list1.stream().filter(o -> !o.getWaringStatus().equals("green")).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(list) || CollectionUtils.isEmpty(list1)) {
            return null;
        }
        double size1 = list2.size();
        double size2 = list3.size();
        double d = Math.abs(size1 - size2) / Math.abs(size2);
        return String.valueOf(d);
    }

    /**
     * 批量删除披露报告
     * @param ids
     */
    @Override
    public void deleteRiskWarningStatus(List<String> ids) throws Exception {
        for (String id:ids){
            RireRiskWarningStatus rireRiskWarningStatus = new RireRiskWarningStatus();
            rireRiskWarningStatus.setId(id);
            List<RireRiskWarningStatus> select = rireRiskWarningStatusMapper.select(rireRiskWarningStatus);
            //rireRiskWarningStatusMapper.selectById(rireRiskWarningStatus);
            if (select.isEmpty()){
                throw new Exception("数据为空");
            }
            try {
                //删除
                RireRiskWarningStatus newWarningStatus = select.get(0);
                RireRiskTarget target = new RireRiskTarget();
                target = (RireRiskTarget) BeanUtils.initBean(target);
                target.setImportGuid(newWarningStatus.getImportGuid());
                target.setRiskId(newWarningStatus.getRiskId());
                target.setImportReportGuid(newWarningStatus.getId());
                target.setQuarterCode(newWarningStatus.getQuarterCode());
                rireRiskTargetMapper.delete(target);

                RiwaRiskWaring waring = new RiwaRiskWaring();
                waring.setImportGuid(newWarningStatus.getImportGuid());
                waring.setRiskId(newWarningStatus.getRiskId());
                waring.setImportReportGuid(newWarningStatus.getId());
                waring.setAcctYear(newWarningStatus.getAcctYear());
                waring.setQuarterCode(newWarningStatus.getQuarterCode());
                waring.setQuarterName(newWarningStatus.getQuarterName());
                waring.setManageCompCode(newWarningStatus.getManageCompCode());
                waring.setManageCompName(newWarningStatus.getManageCompName());
                riskWaringMapper.delete(waring);

                RiwaRiskWaringStatus waringStatus = new RiwaRiskWaringStatus();
                waringStatus.setWarningModelGuid(waring.getId());
                waringStatus.setImportGuid(newWarningStatus.getId());
                waringStatus.setRiskId(newWarningStatus.getRiskId());
                riskWaringStatusMapper.delete(waringStatus);

                RiwaRiskWaringRule waringRule = new RiwaRiskWaringRule();
                waringRule.setImportGuid(newWarningStatus.getId());
                waringRule.setRiskId(newWarningStatus.getRiskId());
                waringRule.setWaringStatusGuid(waringStatus.getId());
                waringRule.setWarningModelGuid(waring.getId());
                riskWaringRuleMapper.delete(waringRule);

                RiwaRiskWaringTarget waringTarget = new RiwaRiskWaringTarget();
                waringTarget.setWarningRuleId(waringRule.getId());
                waringTarget.setImportGuid(newWarningStatus.getId());
                waringTarget.setRiskId(newWarningStatus.getRiskId());
                waringTarget.setWarningModelGuid(waring.getId());
                waringTarget.setWaringStatusGuid(waringStatus.getId());
                riskWaringTatgetMapper.delete(waringTarget);

                int delete = rireRiskWarningStatusMapper.delete(newWarningStatus);
            }catch (Exception e){
                throw new Exception("删除披露报告异常！"+e.getMessage());
            }


        }
    }
}
